package com.lening.community.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.lening.common.base.BaseController;
import com.lening.common.web.Request;
import com.lening.common.web.Result;
import com.lening.community.dto.HouseDto;
import com.lening.community.pojo.House;
import com.lening.community.service.HouseService;
import com.lening.community.service.Record1Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.reactive.function.client.WebClient;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

/**
 * @ToDo:
 * @Author：潘万法
 * @date: 2024/6/3 17:07
 */
@RestController
@RequestMapping("house")
public class HouseController extends BaseController<House, HouseDto, HouseService> {
    @Autowired(required = false)
    private HouseService houseService;
    @Autowired(required = false)
    private WebClient webClient;
    @Autowired(required = false)
    private Record1Service record1Service;

//    @GetMapping("pages")
//    public Page<House> getHouse(HouseDto houseDto) {
//        Page<House> page = houseService.page(houseDto);
//        return page;
//    }

    @GetMapping("getUnit/{HouseHid}")
    public Result<?> getUnit(@PathVariable("HouseHid") Long HouseHid) {
        List<House> bList = houseService.getUnit(HouseHid);
        return Result.ok(bList);
    }

    @GetMapping("getAll")
    public Result<?> getAll() {
//        Result.ok(webClient.get().uri("http://localhost:8082/owner/page",House.class));
        return Result.ok(Request.syncGet("consumer/owner/page", Result.class));
    }


    /**
     * 查询 房屋数量
     */
    @GetMapping("getCount")

    public int getCount() {
        return houseService.getCount();
    }
    //导出
    @PostMapping("ExportExcel")
    public void ExportExcel() {
        // 设置文件导出的路径
        String realPath = "D://wsfile/";
        File folder = new File(realPath);
        if (!folder.isDirectory()){
            folder.mkdirs();
        }
        String fileName = realPath  + "Store" + System.currentTimeMillis() + ".xlsx";
        EasyExcel.write(fileName, House.class).sheet("用户表").doWrite(houseService.find());
    }

    //导入
  //  @Transactional(rollbackFor = Exception.class) // 指定任何异常都要回滚事务
    @PostMapping("ImportExcel")
    public void ImportExcel(MultipartFile multipartFile) throws IOException {

        ExecutorService executorService = Executors.newCachedThreadPool();
        if (multipartFile.isEmpty()) {
            return;
        }
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        // 这里每次会读取3000条数据 然后返回过来 直接调用使用数据就行

        //EasyExcel.read方法用于读取Excel文件
        EasyExcel.read(multipartFile.getInputStream(), House.class, new PageReadListener<House>(dataList -> {
            int filedCount=0;
            //获取文件中的总数
            System.out.println("总条数为"+dataList.size());
            try{
                if(1000<dataList.size()){
                    for(int i = 0; i < 1000000 /1000;i++){
                       //submit： ExecutorService接口的一个方法，返回一个  Future对象来表示异步计算的结果。
                        Future<Boolean> result = executorService.submit(() -> {
                            return houseService.saveBatch(dataList);
                            //saveBatch只能添加1000条
                            //调用houseService.saveBatch方法将数据批量保存到数据库中
                        });
                    }
                }else {
                    for (House house : dataList) {
                        try {
                            if (house.getRoomNumber() ==null) {
                                throw new IllegalArgumentException("Invalid value for someField: ");
                            }
                            //调用insert方法将导入的数据用mybatisPlus一个个添加进数据库
                            houseService.insert(house);
                        }catch(Exception e){
                            filedCount++;
                            log.print("导入失败，失败数为"+filedCount);
                        }
                    }
                    record1Service.adda((long) dataList.size(),(long) dataList.size()-filedCount, (long) filedCount);
                }
            }catch (Exception e){
                log.print("导入失败，失败数为"+filedCount);

            }
        })).sheet().doRead();
    }
}
